<?php
if (!defined('APP_ID')) { die('No direct script access allowed'); }

class File {
	public static function formatSize($bytes) {
		$sizes = array('B', 'KB', 'MB', 'GB', 'TB', 'xB');
		$size = (float) $bytes;
		$curr = 0;
		while ($size > 1024) {
			$size /= 1024;
			$curr++;
		}
		return sprintf('%.2f %s', $size, $sizes[$curr]);
	}

	public static function getIcon($ext = 'unknown') {
		$ext = strtolower(trim($ext));
		$icon_file = 'unknown.png';
		switch ($ext) {
			case 'avi':
			case 'wmv': $icon_file = 'avi.png'; break;
			case 'pdf': $icon_file = 'pdf.png'; break;
			case 'rtf':
			case 'doc': $icon_file = 'doc.png'; break;
			case 'txt': $icon_file = 'txt.png'; break;
			case 'xls': $icon_file = 'xls.png'; break;
		}
		return $icon_file;
	}

	public static function getUniqueName($file_name) {
		$result = '';
		
		$file_info = pathinfo($file_name);
		$result = md5($file_info['filename'] . '-' . uniqid());
		$result .= '.' . trim(strtolower($file_info['extension']));
		
		return $result;
	}
	/**
	 * Return file info
	 */
	public static function getInfo($id, $fields = '*') {
		return Query::factory('select')
			->table('tbl_files')
			->fields($fields)
			->where('id=%d', $id)
			->limit(1)
			->execute()
			->row();
	}

	/**
	 * Return list of categories
	 */
	public static function inCategories($id) {
		$result = array();
		$rows = Query::factory('select')
			->table('tbl_file2category')
			->fields('category_id')
			->where('file_id=%d', $id)
			->execute()
			->rows();

		foreach ($rows as $row) {
			$result[] = intval($row['category_id']);
		}
		return $result;
	}

	/**
	 * Return list of files
	 */
	public static function getList($id = 0) {
		$query = Query::factory('select')
			->table('tbl_files', 'f')
			->fields('f.*')
			->where('f.status_id IN (1,2)');
		
		if ($id > 0) {
			$query->join('tbl_file2category', 'f2c', Query::JOIN_INNER)
				->on('f.id=f2c.file_id')
				->where('f2c.category_id=%d', $id)
				->orderBy('f2c.sequence', Query::ORDER_ASC);
		} else {
			$query->join('tbl_file2category', 'f2c', Query::JOIN_OUTER_LEFT)
				->on('f.id=f2c.file_id')
				->where('f2c.category_id IS NULL');
		}
		
		$query->orderBy('f.id', Query::ORDER_ASC);
		
		return $query->execute()->rows();
	}

	/**
	 * Insert document
	 */
	public static function insert($data) {
		return Query::factory('insert')
			->table('tbl_files')
			->data($data)
			->execute()
			->getLastId();
	}

	/**
	 * Update document
	 */
	public static function update($id, $data) {
		$query = Query::factory('update')
			->table('tbl_files')
			->data($data)
			->where('id=%d', $id)
			->execute();
		return ($query->getAffectedRows() > -1);	
	}

	/**
	 * Delete document
	 */
	public static function delete($id, $data) {
		$result = false;
		$file_info = self::getInfo($id, 'name,name_thumb');
		$cat_list = self::inCategories($id);
		
		$query = Query::factory('update')
			->table('tbl_files')
			->data($data)
			->where('id=%d', $id)
			->execute();
		if ($query->getAffectedRows() > -1) {
			$result = true;
		}
		
		if (!empty($file_info['name'])) {
			self::deleteFile($file_info['name']);
		}

		if (!empty($file_info['name_thumb'])) {
			self::deleteFile($file_info['name_thumb']);
		}
		
		if (count($cat_list) > 0) {
			foreach ($cat_list as $cat) {
				$data = array();
				Query::data($data, 'sequence', 0, Query::DATA_INTEGER);
				Query::factory('update')
					->table('tbl_file2category')
					->data($data)
					->where('file_id=%d', $id)
					->where('category_id=%d', $cat)
					->execute();
				
				self::fixSequence($cat);
			}
		}
		
		return $result;
	}

	/**
	 * Delete document
	 */
	public static function deleteFile($file_name) {
		$old_path = DATA_DIR . 'upload/' . $file_name;
		$new_path = DATA_DIR . 'delete/' . $file_name;
		rename($old_path, $new_path);
	}

	/**
	 * Add file to category
	 */
	public static function addToCategory($file_id, $cat_id) {
		$result = false;
		
		if (($file_id > 0) && ($cat_id > 0) && !self::inCategory($file_id, $cat_id)) {
			$data = array();
			Query::data($data, 'file_id', $file_id, Query::DATA_INTEGER);
			Query::data($data, 'category_id', $cat_id, Query::DATA_INTEGER);
			
			$id = Query::factory('insert')
				->table('tbl_file2category')
				->data($data)
				->execute()
				->getLastId();
			
			if ($id) {
				self::fixSequence($cat_id);
				$result = true;
			}
		}
		
		return $result;
	}

	/**
	 * Remove file from category
	 */
	public static function removeFromCategory($file_id, $cat_id) {
		$result = false;
		
		if (($file_id > 0) && ($cat_id > 0) && self::inCategory($file_id, $cat_id)) {
			$query = Query::factory('delete')
				->table('tbl_file2category')
				->where('file_id=%d', $file_id)
				->where('category_id=%d', $cat_id)
				->execute();
			if (!$query->isError()) {
				self::fixSequence($cat_id);
				$result = true;
			}
		}
		
		return $result;
	}

	/**
	 * Remove file from category
	 */
	public static function moveToCategory($file_id, $cat_id) {
		$categories = self::inCategories($file_id);
		if (count($categories) > 0) {
			if (intval($categories[0]) != intval($cat_id)) {
				self::removeFromCategory($file_id, $categories[0]);
				self::addToCategory($file_id, $cat_id);
			}
		} else if ($cat_id > 0) {
			self::addToCategory($file_id, $cat_id);
		}
	}

	/**
	 * Is file in category
	 */
	public static function inCategory($file_id, $cat_id) {
		$result = false;
		
		$file_id = intval($file_id);
		$cat_id = intval($cat_id);
		
		if (($file_id > 0) && ($cat_id > 0)) {
			$query = Query::factory('select')
				->table('tbl_file2category')
				->fields('id')
				->where('file_id=%d', $file_id)
				->where('category_id=%d', $cat_id)
				->limit(1)
				->execute();
			if ($query->row()) {
				$result = true;
			}
		}

		return $result;
	}

	public static function fixSequence($id) {
		$list = Query::factory('select')
			->table('tbl_file2category', 'f2c')
			->fields('f2c.id')
			->join('tbl_files', 'f', Query::JOIN_INNER)
			->on('f2c.file_id=f.id')
			->where('f2c.category_id=%d', $id)
			->where('f.status_id IN (1,2)')
			->orderBy('f2c.sequence', Query::ORDER_ASC)
			->orderBy('f.id', Query::ORDER_ASC)
			->execute()
			->rows();

		$sequence = 1;
		foreach ($list as $item) {
			$data = array();
			Query::data($data, 'sequence', $sequence, Query::DATA_INTEGER);
			$id = Query::factory('update')
				->table('tbl_file2category')
				->data($data)
				->execute();
			$sequence++;
		}
	}
}